//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    var that=this;

    this.validateopenid=function(callback){
      if (!that.globalData.openid) {
        return;
      }
      if (that.globalData.token && that.globalData.token.length>0){
        wx.request({
          method: 'GET',
          url: that.globalData.serverPath + "api/bs-users/account",
          header: {
            'Authorization': that.globalData.token
          },
          success: function (res) {
            if (res.statusCode != 200) {

            } else {
              if (res.data.sysuser) {
                //openid正确，用户未被其他用户绑定。
                if (that.globalData.openid == res.data.sysuser.openid) {
                  if (res.data.bsuser) {
                    that.globalData.bususer = res.data.bsuser;
                  }
                  if (callback) {
                    callback();
                  }
                } else {
                  wx.showModal({
                    title: '系统提示',
                    content: '您的账号已经被其他用户绑定',
                    showCancel: false,
                    success: function () {
                      that.resetbind();
                    }
                  })
                }
              }
            }
          }
        });
      }else{
        that.processLogin(that.globalData.loginresult, function () {
          wx.reLaunch({
            url: '../main-driver/main-driver'
          });
        });
      }
     
    }

   this.resetbind=function(){
     that.globalData.loginfinish = false;
     that.globalData.loginresult = null;
     that.globalData.token = null;
     that.globalData.userInfo = null;
     that.globalData.bususer = null;
     that.globalData.openid = null;

     that.initApp(function () {
       that.processLogin(that.globalData.loginresult, function () {
         wx.reLaunch({
           url: '../main-driver/main-driver'
         });
       });
     });
   }

    //接收用户登录结果
    this.processLogin=function(result,callback){
      if (result.errorCode > 0) {
        //获取微信openid出错。
        wx.showModal({
          title: '错误提示',
          content: '微信授权登录错误【' + result.errorCode + '】',
          showCancel: false
        })
      } else {
        if (result.result == 0 && result.message == "微信用户身份未绑定。") {
          if (result.data.openid) {
            that.globalData.openid = result.data.openid;
            //跳转到用户绑定界面
            wx.navigateTo({
              url: '../bangding/bangding'
            })
            wx.hideLoading();
          } else {
            wx.showModal({
              title: '错误提示',
              content: '获取微信授权身份错误',
              showCancel: false
            })
          }
        } else {
          if (result.id_token) {
            that.globalData.token = "Bearer " + result.id_token;
          }
          wx.request({
            method: 'GET',
            url: that.globalData.serverPath + "api/bs-users/account",
            header: {
              'Authorization': that.globalData.token
            },
            success: function (res) {
              console.log(res);
              if (res.data.sysuser) {
                that.globalData.openid = res.data.sysuser.openid;
              }
              if (res.data.bsuser) {
                that.globalData.bususer = res.data.bsuser;
              }
              //标记登录成功
              that.globalData.loginfinish=true;

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (that.userInfoReadyCallback) {
                that.userInfoReadyCallback()
              }
              if (callback) {
                callback(res);
              }
            }
          })
        }
      }
    }

    //用户登录，并初始化应用
    this.initApp=function(callback){
      
      // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
      wx.getUserInfo({ 
        success: res => {
          // 可以将 res 发送给后台解码出 unionId
          this.globalData.userInfo = res.userInfo;
        }
      });
      // 登录
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (res.code) {
            var that = this;
            //发起网络请求
            wx.request({
              url: that.globalData.serverPath + "api/authenticate/wechat/" + res.code,
              data: {
              },
              method: 'GET',
              success: function (res) {
                console.log(res);
                //记录登录返回结果
                that.globalData.loginresult=res.data;
                //that.processLogin(that.globalData.loginresult); 
                if (callback) {
                  callback(res);
                }
              },
              fail: function (err) {
                wx.reLaunch({
                  url: 'main-driver/main-driver'
                })
              }
            })
          } else {
            console.log('获取用户登录态失败！' + res.errMsg)
          }
        }
      })
    }

   //this.initApp();
    

    wx.getSystemInfo({
      success: function (res) {
        console.log("systeminfo",res);
        that.globalData.screenHeight = res.screenHeight;
        that.globalData.screenWidth=res.screenWidth;
        that.globalData.windowHeight = res.windowHeight;
        that.globalData.windowWidth = res.windowWidth;
      },
    })

    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        console.log("getlocation>>>",res);
        that.globalData.latitude = latitude;
        that.globalData.longitude = longitude;
      },
      fail:function(error){
        console.log("getlocation>>>", error);
        wx.showModal({
          title: '定位错误',
          content: '请允许微信访问地理位置。',
          showCancel:false,
          success:function(){
            wx.switchTab({
              url: '../main-driver/main-driver'
            });
          }
        })
      }
    })
   
  },

  currentMass:null,

  setCurrentMass:function(mass){
    this.currentMass=mass;
  },
  getCurrentMass:function(){
    return this.currentMass;
  },
  globalData: {
    loginfinish:false,
    loginresult:null,
    latitude:null,
    longitude:null,
    screenHeight:null,
    screenWidth:null,
    openid:null,
    userInfo: null,
    serverPath:"https://www.dbk365.cn/swservice/",
    errorInfo:null,
    bususer:null,
    token:null,
    islaunch:false,
    checkCar:null,
    checkDriver:null
  }
})